<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #loginUserId="{ model, field }">
        <ApiSelect
          showSearch
          v-model:value="model[field]"
          :filterOption="false"
          placeholder="请输入用户名"
          resultField="data"
          labelField="userName"
          valueField="id"
          @search="onSearch"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, ApiSelect, useForm } from "/@/components/Form/index"
  import { formSchema } from "./mchInfo.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateMch, getMchInfo } from "/@/api/pay"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { list as listUser } from "../../system/user/user.api"
  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      rowId.value = data.record.mchNo
    }
    const mchInfo = await getMchInfo({ mchNo: data.record.mchNo })

    // 无论新增还是编辑，都可以设置表单值
    if (typeof mchInfo === "object") {
      setFieldsValue({
        ...mchInfo,
      })
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter })
  })
  const getTitle = computed(() => (!unref(isUpdate) ? "新增商户" : "编辑商户"))

  const onSearch = (value: string) => {
    console.log("search value: ", value)
  }
  async function handleSubmit() {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      values.userIdentity === 1 && (values.deptIds = "")
      await saveOrUpdateMch(values, unref(isUpdate))
      createMessage.success(`${getTitle.value}成功`)
      closeDrawer()
      emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
